package com.zlq.cn.service.un;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zlq.cn.api.ResponseException;
import com.zlq.cn.bootstrap.SignApiBootstrap;
import com.zlq.cn.cache.RedisCacheService;
import com.zlq.cn.cache.RedisKey;
import com.zlq.cn.config.FinderConfiguration;
import com.zlq.cn.dto.SmsImeiCountDTO;
import com.zlq.cn.dto.param.SendSmsParam;
import com.zlq.cn.entity.SmsRecord;
import com.zlq.cn.mapper.un.SmsRecordMapper;
import com.zlq.cn.util.ImeiUtil;
import com.zlq.cn.util.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDate;
import java.time.LocalDateTime;

/**
 * <p>
 * 短信记录 服务实现类
 * </p>
 *
 * @author zhoucl
 * @since 2020-08-24
 */
@Service
public class SmsRecordService extends ServiceImpl<SmsRecordMapper, SmsRecord> {
    protected Logger logger = LoggerFactory.getLogger(getClass().getName());
    @Resource
    private FinderConfiguration finderConfiguration;
    @Resource
    private RedisCacheService redisCacheService;
    @Resource
    private IAcsClient iAcsClient;

    @Bean
    public IAcsClient iAcsClient() {
        DefaultProfile profile = DefaultProfile.getProfile(finderConfiguration.getRegionId(),
                finderConfiguration.getAliyunAccessKeyId(),
                finderConfiguration.getAliyunAccessSecret());
        return new DefaultAcsClient(profile);
    }

    public String sendSms(String mobile, String content) {
        if (redisCacheService.hasKey(RedisKey.createSmsKey(mobile))) {
            ResponseException.resultApiError("发送频繁，请稍后再试");
        }
        redisCacheService.set(RedisKey.createSmsKey(mobile), mobile, 60);
        String msg = "您的验证码为：" + content + ",验证码五分钟内有效，请勿泄露于他人";
        CommonRequest request = new CommonRequest();
        request.setSysMethod(MethodType.POST);
        request.setSysDomain(finderConfiguration.getSmsDomain());
        request.setSysVersion("2017-05-25");
        request.setSysAction("SendSms");
        request.putQueryParameter("RegionId", finderConfiguration.getRegionId());
        request.putQueryParameter("PhoneNumbers", mobile);
        request.putQueryParameter("SignName", finderConfiguration.getSmsSignName());
        request.putQueryParameter("TemplateCode", finderConfiguration.getSmsTemplateCode());
        request.putQueryParameter("TemplateParam", "{\"code\" : \"" + content + "\"}");
        try {
            CommonResponse response = iAcsClient.getCommonResponse(request);
            JSONObject jsonObject = JSON.parseObject(response.getData());
            if ("OK".equals(jsonObject.getString("Code"))) {
                return msg;
            }
            ResponseException.resultApiError(jsonObject.getString("Message"));
        } catch (Exception e) {
            ResponseException.resultApiError("短信发送失败");
        }
        return msg;
    }

    public boolean findCheckSmsVcode(String mobile, String vcode, String smsType) {
        logger.error("手机号==>{},验证码==>{}", mobile, vcode);
//        if (FinderConfiguration.DEV.equals(finderConfiguration.getProfile())) {
//            return true;
//        }
        if ("13135325001".equals(mobile)) {
            return "8888".equals(vcode);
        }
        return getOne(new LambdaQueryWrapper<SmsRecord>()
                .eq(SmsRecord::getMobile, mobile)
                .eq(SmsRecord::getVcode, vcode)
                .eq(SmsRecord::getType, smsType)
                .ge(SmsRecord::getEndtime, LocalDateTime.now())
                .orderByDesc(SmsRecord::getEndtime), false) != null;
    }

    public void sendSmsCheckImei(SendSmsParam sendSmsParam) {
        // imei校验不通过直接提示成功
        String imei = SignApiBootstrap.get().getImei();
        if (!ImeiUtil.checkImei(imei)) {
            log.error("imei检验未通过" + imei);
            return;
        }
        if (SmsRecord.SMS_TYPE_LOGIN.equals(sendSmsParam.getSmsType())) {

        } else {
            ResponseException.resultApiError("该短信类型不支持");
        }
        SmsImeiCountDTO smsImeiCountDTO = redisCacheService.get(RedisKey.createSmsImeiKey(imei));
        if (smsImeiCountDTO == null) {
            smsImeiCountDTO = new SmsImeiCountDTO(imei, 0, LocalDate.now());
        }
        // 不是同一天次数重置
        if (!smsImeiCountDTO.getDate().equals(LocalDate.now())) {
            smsImeiCountDTO.setDate(LocalDate.now())
                    .setCount(0);
        } else if (smsImeiCountDTO.getCount() >= 10) {
            ResponseException.resultApiError("当天发送次数超过上限");
        }
        smsImeiCountDTO.setCount(smsImeiCountDTO.getCount() + 1);
        redisCacheService.set(RedisKey.createSmsImeiKey(imei), smsImeiCountDTO, 60 * 60 * 24);
        String vcode = StringUtils.getRandomByLength(4);
        this.sendSms(sendSmsParam.getPhone(), vcode);
        SmsRecord smsRecord = new SmsRecord();
        smsRecord.setType(sendSmsParam.getSmsType());
        smsRecord.setVcode(vcode);
        smsRecord.setSendtime(LocalDateTime.now());
        smsRecord.setBuildtime(LocalDateTime.now());
        smsRecord.setEndtime(LocalDateTime.now().plusMinutes(5));
        smsRecord.setMobile(sendSmsParam.getPhone());
        smsRecord.setMsg(vcode);
        smsRecord.setStatus(1);
        this.save(smsRecord);
    }
}
